#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <cstdio>

int ticket = 1000;

pthread_spinlock_t lock;

void* buyticket(void* arg){
	char* id = (char*)arg;
	while(ticket){
		pthread_spin_lock(&lock);
		if(ticket > 0){	
			printf("线程%s 抢到第%d张票\n",id,ticket);
			ticket--;
			usleep(1000);
			pthread_spin_unlock(&lock);
		}
		else{
			printf("票已售空\n");
			sleep(1);
			pthread_spin_unlock(&lock);
			break;
		}
	}

	return nullptr;
}

int main()
{
	pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE);

	pthread_t t1, t2, t3, t4;
	pthread_create(&t1, nullptr, buyticket, (void*)" 1 ");
	pthread_create(&t2, nullptr, buyticket, (void*)" 2 ");
	pthread_create(&t3, nullptr, buyticket, (void*)" 3 ");
	pthread_create(&t4, nullptr, buyticket, (void*)" 4 ");

	pthread_join(t1, nullptr);
	pthread_join(t2, nullptr);
	pthread_join(t3, nullptr);
	pthread_join(t4, nullptr);

	pthread_spin_destroy(&lock);

	return 0;
}